#  django
from django.shortcuts import render
from django.contrib.auth.models import User
#  rest_framework
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework import generics
#  导入models
from oauth2_provider.models import (
    Application, AccessToken, RefreshToken, Grant,
)
#  导入serializers
from authApp.serializers import (
    AppSerializer, UserSerializer, SignUpSerializer
)

#  自定义
#  permission
from authApp.permission import IsAuthenticatedOrCreate


# Create your views here.
class AppViewSet(viewsets.ModelViewSet):
    queryset = Application.objects.all()
    serializer_class = AppSerializer

    def list(self, request, *arg, **kargs):
        app_name = request.GET.get('name')

        if app_name is not None:
            queryset = self.queryset.filter(name=app_name)
        else:
            queryset = self.queryset

        #  分页
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class TokenViewSet(viewsets.ModelViewSet):
    pass

class SignUpViewSet(generics.CreateAPIView):
    queryset = User.objects.all()
    serializer_class = SignUpSerializer
    permission_classes = (IsAuthenticatedOrCreate,)

